<?php

class FeedStorageAdapter implements IFeedStorageAdapter 
{
    public function hasFeed($name)
    {
        if(!$name) return false;
        
        $feedTable = new FeedModel();
        $select = $feedTable->select()
            ->where('name = ?',$name)
            ->where('enabled = 1')
        ;
        $feed = $feedTable->fetchRow($select);
        
        return $feed!==null;
    }
    
    public function createFeed($name,$data=array(),$initialEntries=array())
    {
        $feedTable = new FeedModel();

        if(!@$name) throw new NullException("No name specified");
        $data['name'] = $name;
        if(!@$data['created']) $data['created'] = date('Y-m-d H:i:s',time());
        if(!@$data['updated']) $data['updated'] = date('Y-m-d H:i:s',time());
        
        $feedTable->insert($data);
        
        return true;
    }
    
    public function getFeed($name)
    {
        $feedTable = new FeedModel();
        $select = $feedTable->select()
            ->where('name = ?',$name)
            ->where('enabled = 1')
        ;
        $feed = $feedTable->fetchRow($select);
        if($feed===null)
        {
            throw new NotFoundException("Feed '$name' does not exist");
        }
        return $feed;
    }
    
    public function getFeeds()
    {
        $feedTable = new FeedModel();
        $select = $feedTable->select()
            ->where('enabled = 1')
        ;
        $feeds = $feedTable->fetchAll($select);
        if(count($feeds)===0)
        {
            throw new NotFoundException("No feeds found");
        }
        return $feeds;
    }
    
    public function deleteFeed($name)
    {
        $feedTable = new FeedModel();
        $select = $feedTable->select()
            ->where('name = ?',$name)
        ;
        $feed = $feedTable->fetchRow($select);
        $feed->delete();
        return true;
    }
}